<template>
	<view class="select-members">
		<!-- 成员列表 -->
		<view class="member-list">
			<block v-for="(friend, index) in friends" :key="index">
				<view 
					v-if='friend.status === "accepted" && !isInGroup(friend)'
					class="member-item" 
					@click="toggleSelect(friend)"
					:class="{ selected: isSelected(friend) }"
				>
					<image :src="friend.friendAvatar" mode="aspectFill" />
					<text>{{ friend.friendName }}</text>
				</view>
				
				<view v-else class="member-item disabled">
					<image :src="friend.friendAvatar" mode="aspectFill" />
					<text>{{ friend.friendName }}（已在群内）</text>
				</view>
			</block>
		</view>

		<!-- 邀请按钮 -->
		<view class="invite-button">
			<button type="primary" @click="inviteMembers">邀请选中好友进群</button>
		</view>
	</view>
</template>

<script>
import {UserFriendApi,GroupMembersApi} from '@/api/index.js'
import websocketMixin from '@/utils/mixins/websocketMixin'

export default {
	mixins: [websocketMixin],
	data() {
		return {
			friends: [],
			selected: [],
			groupId: null,
			currentMembers: [] 
		};
	},
	onLoad(options) {
	    this.groupId = options.groupId; // 从页面加载选项中获取groupId
	    if (!this.groupId) {
	      uni.showToast({
	        title: '群组ID未指定',
	        icon: 'none'
	      });
	    }
	  },
	mounted() {
		this.getFriends();
		this.getCurrentGroupMembers();
	},
	methods: {
		// 获取当前登陆用户好友列表
		async getFriends() {
			const res = await UserFriendApi.getFriends();
			console.log(res);
			this.friends = res.data;
		},
		// 判断用户是否是群成员
		isInGroup(friend) {
			const friendId = friend.friendId;
			return this.currentMembers.some(member => member === friendId);
		},
		// 获取当前群成员列表
		async getCurrentGroupMembers() {
			try {
				const res = await GroupMembersApi.getMembers(this.groupId); 
				this.currentMembers = res.data || [];
			} catch (err) {
				console.error('获取群成员失败', err);
			}
		},
		// 点击切换选中状态（只允许未入群的好友被选中）
		toggleSelect(friend) {
			if (this.isInGroup(friend)) return; // 如果已在群中，则不可选

			const index = this.selected.findIndex(item => item.friendId === friend.friendId);
			index === -1 ? this.selected.push(friend) : this.selected.splice(index, 1);
		},
		isSelected(friend) {
			return this.selected.some(item => item.friendId === friend.friendId);
		},
		async inviteMembers() {
		    if (this.selected.length === 0) {
		      uni.showToast({
		        title: '请选择要邀请的好友',
		        icon: 'none'
		      });
		      return;
		    }
	
		    if (!this.groupId) {
		      uni.showToast({
		        title: '群组ID未指定',
		        icon: 'none'
		      });
		      return;
		    }
	
		    // 提取被选中用户的 friendId 列表
		    const userIds = this.selected.map(friend => friend.friendId);
	
		    try {
		      // 调用接口邀请用户进群
		      const res = await GroupMembersApi.inviteUsers(this.groupId, userIds);
	
		      uni.showToast({
		        title: `已邀请${userIds.length}位好友,等待他们同意`,
		        icon: 'success'
		      });
	
		      // 返回上一页
		      setTimeout(() => {
		        uni.navigateBack('/pages/groups/group_details');
		      }, 1000);
	
		    } catch (error) {
		      uni.showToast({
		        title: '邀请失败，请重试',
		        icon: 'none'
		      });
		      console.error('邀请出错:', error);
		    }
		}
	}
};
</script>

<style lang="scss" scoped>
.select-members {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.member-list {
	padding: 30rpx;
	background-color: #fff;
}

.member-item {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
	padding: 20rpx;
	border-radius: 16rpx;

	image {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		margin-right: 20rpx;
	}

	&.selected {
		background-color: #e8f5e9;
	}
}

.invite-button {
	padding: 30rpx;
	background-color: #fff;
}
</style>